import { defineStore } from "pinia";
import { ElMessage } from "element-plus";

import { PlayListDetail } from "@/types/album";
import {
  getUsersPlaylist,
  getMyLikedMusic,
  CDMusicInPlaylist,
} from "@/api/album";

const useUserMusicSourceStore = defineStore("userMusicSource", {
  state: () => ({
    playlists: [] as PlayListDetail[],
    userLikedMusics: [] as (string | number)[],
  }),
  actions: {
    async queryUserPlaylist(uid: string | number) {
      try {
        const res = await getUsersPlaylist(uid);
        if (res.code === 200) {
          this.playlists = res.playlist;
        }
      } catch (err) {
        console.error(err);
      }
    },
    async queryUserLikedMusic(uid: string | number) {
      try {
        const res = await getMyLikedMusic(uid);
        if (res.code === 200) {
          this.userLikedMusics = res.ids;
        }
      } catch (err) {
        console.log(err);
      }
    },
    async likeMusic(tracks: number | string) {
      if (!this.myLikedPlaylistId) {
        return;
      }
      try {
        const res = await CDMusicInPlaylist(
          "add",
          this.myLikedPlaylistId,
          tracks
        );
        if (res.status === 200) {
          console.log(res);
          ElMessage.success("操作成功");
          this.userLikedMusics.unshift(tracks);
        }
      } catch (err) {
        console.error(err);
      }
    },
    async dislikeMusic(tracks: number | string) {
      if (!this.myLikedPlaylistId) {
        return;
      }
      try {
        const res = await CDMusicInPlaylist(
          "del",
          this.myLikedPlaylistId,
          tracks
        );
        if (res.status === 200) {
          console.log(res);
          ElMessage.success("操作成功");
          const temp = this.userLikedMusics.filter((s) => s !== tracks);
          this.userLikedMusics = temp;
        }
      } catch (err) {
        console.error(err);
      }
    },
  },
  getters: {
    myCreatedPlaylist(state): PlayListDetail[] {
      return state.playlists.filter((item, idx) => {
        return item.subscribed === false && idx !== 0;
      });
    },
    mySubscribedPlaylist(state): PlayListDetail[] {
      return state.playlists.filter((item) => item.subscribed === true);
    },
    myLikedPlaylist(state): PlayListDetail[] {
      return state.playlists.filter((item, idx) => {
        return item.subscribed === false && idx === 0;
      });
    },
    myLikedPlaylistId(state): number | string {
      let result = -1;
      const data = state.playlists.find((item, idx) => {
        return item.subscribed === false && idx === 0;
      });

      if (data) {
        result = data.id;
      }
      return result;
    },
  },
});

export default useUserMusicSourceStore;
